package com.lsq.baseadmin.common.interceptor;

import com.lsq.baseadmin.common.component.SpringContextUtils;
import com.lsq.baseadmin.common.exception.MyException;
import com.lsq.baseadmin.modules.manage.service.UserService;
import com.lsq.baseadmin.modules.manage.service.impl.UserServiceImpl;
import com.lsq.baseadmin.modules.manage.vo.AuthUser;
import com.lsq.baseadmin.modules.manage.vo.UserVo;
import com.lsq.baseadmin.modules.manage.utils.AuthUtil;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sojan-lsq
 * @since 2020/10/24 11:53
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            UserVo loginUser = AuthUtil.getLoginUser(request.getSession());
            if(loginUser != null) {
                return true;
            }
            // 没在session 并且cookie没有信息，表示未登录
            Cookie[] cookies = request.getCookies();
            if(cookies == null || cookies.length < 1) {
                throw new MyException(HttpStatus.UNAUTHORIZED, "您未登录或登录已过期，请重新登录！");
            }

            AuthUser authUser = new AuthUser();
            for (Cookie cookie : cookies){
                if("username".equals(cookie.getName())) {
                    authUser.setUsername(cookie.getValue());
                }
                if("password".equals(cookie.getName())) {
                    authUser.setPassword(cookie.getValue());
                }
            }
            // cookie没有用户名和密码
            if(!StringUtils.hasText(authUser.getUsername()) || !StringUtils.hasText(authUser.getPassword())) {
                throw new MyException(HttpStatus.UNAUTHORIZED, "您未登录或登录已过期，请重新登录！");
            }

            UserService userService = (UserServiceImpl)SpringContextUtils.getBean("userServiceImpl");
            UserVo userVo = userService.login(authUser);
            AuthUtil.setLoginUser(userVo, request.getSession());
        }

        return true;
    }

}
